package com.imay.live.activity.discovery;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.activity.BaseActivity;
import com.imay.live.fragment.dynamics.LinearFragment;
import com.imay.live.model.FeedModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.R;

import java.util.ArrayList;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by liangzhenxiong on 2017/04/14 0014.
 * 话题动态页
 */

public class TopicDynamicActivity extends BaseActivity {
    final static String TITLE = "title";
    public final static String MODELID = "FeedModelID";
    int feedid;
    String title;
    int count = 13;
    LinearFragment linearFragment;
    private ImageView progress;
    private TextView load_text;
    private View load_layout;

    public static void start(Context context, int Feedid, String title) {
        Intent starter = new Intent(context, TopicDynamicActivity.class);
        starter.putExtra(TITLE, title);
        starter.putExtra(MODELID, Feedid);
        starter.putExtra(LinearFragment.FOLLOW, true);
        starter.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(starter);
    }

    public void loadError(String error) {
        load_text.setVisibility(View.VISIBLE);
        load_layout.setVisibility(View.VISIBLE);
        load_text.setText(error);
        progress.clearAnimation();
        progress.setImageResource(R.mipmap.wushuju);
        linearFragment.setLoadFinish();
        linearFragment.setRefreshFinish();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.topicactivity_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        title = getIntent().getStringExtra(TITLE);
        feedid = getIntent().getIntExtra(MODELID, 0);
        if (!TextUtils.isEmpty(title)) {
            title = title.trim();
            setTitle(getResources().getString(R.string.search_topiccontent, title));
        }
        initLoadLayout();
        initLoad(feedid);
    }

    private void refreshLoad(int maxfeedid, boolean include) {
        ProtoRequestHelper.task(ProtoHttpFactory.getFeedAllInfo(title, 0, maxfeedid, count, false)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<FeedModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<FeedModel>>>() {
                    }.getType());

                    if (result.result == CodeSuccess) {
                        ArrayList<Object> list = new ArrayList<Object>();
                        for (FeedModel feedModel : result.data) {
                            list.add(0, feedModel);
                        }
                        if (list.size() >= count) {
                            linearFragment.getmRefreshLayout().setEnableRefresh(true);
                        } else {
                            linearFragment.getmRefreshLayout().setEnableRefresh(false);
                        }
                        linearFragment.replaceDatas(0, list);
                    } else {
                    }
                    linearFragment.setRefreshFinish();


                } catch (Exception e) {
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
            }
        });
    }

    private void initLoad(int maxId) {
        ProtoRequestHelper.task(ProtoHttpFactory.getFeedAllInfo(title, maxId, 0, count, true)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<FeedModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<FeedModel>>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        progress.clearAnimation();
                        load_layout.setVisibility(View.GONE);
                        ArrayList<Object> list = new ArrayList<Object>();
                        list.addAll(result.data);
                        if (list.size() >= count) {
                            linearFragment.getmRefreshLayout().setEnableLoadmore(true);
                        } else {
                            linearFragment.getmRefreshLayout().setEnableLoadmore(false);
                        }
                        linearFragment.setDatas(list);
                    } else {
                        loadError(getResources().getString(R.string.str_nodata));
                    }
                    linearFragment.setLoadFinish();

                } catch (Exception e) {
                    loadError(getResources().getString(R.string.str_nodata));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadError(getResources().getString(R.string.str_nodata));
            }
        });
    }

    void initLoadLayout() {
        load_layout = $(R.id.load_layout);
        progress = (ImageView) load_layout.findViewById(R.id.progress_icon);
        load_text = (TextView) load_layout.findViewById(R.id.load_text);
//        error = context.getResources().getString(R.string.str_nodata);
        load_layout.setVisibility(View.VISIBLE);
        ((AnimationDrawable) progress.getDrawable()).start();
        linearFragment = LinearFragment.newInstance();
        addFragment(linearFragment);
    }

    public void onRefresh() {
        if (linearFragment.getManager().getmAdapter().getData().size() > 0) {
            if (linearFragment.getManager() != null) {
                FeedModel feedModel = (FeedModel) linearFragment.getManager().getmAdapter().getData().get(0);
                refreshLoad(feedModel.getFeedId(), false);
            } else {
                refreshLoad(feedid, false);
            }
        } else {
            refreshLoad(feedid, false);
        }

    }

    public void onLoadMore() {
        if (linearFragment.getManager().getmAdapter().getData().size() > 0) {
            if (linearFragment.getManager() != null) {
                FeedModel feedModel = (FeedModel) linearFragment.getManager().getmAdapter().getData().get(linearFragment.getManager().getmAdapter().getData().size() - 1);
                moreLoad(feedModel.getFeedId());
            } else {
                moreLoad(feedid);
            }
        } else {
            moreLoad(feedid);
        }
    }

    private void addFragment(Fragment loadFragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(loadFragment.getClass().toString());
        if (fragment == null) {
            transaction.add(R.id.fragment_id, loadFragment, loadFragment.getClass().toString());
        }
        transaction.show(loadFragment);
        transaction.commitAllowingStateLoss();
    }

    private void moreLoad(int sinceId) {
        ProtoRequestHelper.task(ProtoHttpFactory.getFeedAllInfo(title, sinceId, 0, 20, false)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<FeedModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<FeedModel>>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        ArrayList<Object> list = new ArrayList<Object>();
                        list.addAll(result.data);
                        if (list.size() >= count) {
                            linearFragment.getmRefreshLayout().setEnableLoadmore(true);
                        } else {
                            linearFragment.getmRefreshLayout().setEnableLoadmore(false);
                        }
                        linearFragment.addDatas(list);
                    } else {
                        loadError(getResources().getString(R.string.str_nodata));
                    }

//                    loadViewControl.moreLoadView(result.data, result.result);

                } catch (Exception e) {
//                    loadViewControl.loadError();
                    loadError(getResources().getString(R.string.str_nodata));
                    linearFragment.getmRefreshLayout().setEnableLoadmore(false);
                }
                linearFragment.setLoadFinish();
            }

            @Override
            public void onRequestError(String command, int code, String message) {
//                loadViewControl.loadError(message);
                loadError(getResources().getString(R.string.str_nodata));
                linearFragment.getmRefreshLayout().setEnableLoadmore(false);
            }
        });
    }


}
